from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_sqlalchemy import SQLAlchemy
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///items.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = 'static/uploads'

# 确保上传文件夹存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

db = SQLAlchemy(app)

# 数据库模型
class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    price = db.Column(db.Float, nullable=False)
    description = db.Column(db.Text, nullable=False)
    category = db.Column(db.String(50), nullable=False)
    contact = db.Column(db.String(100), nullable=False)
    image = db.Column(db.String(200), nullable=True)

# 创建数据库表
with app.app_context():
    db.create_all()

# 首页
@app.route('/')
def index():
    items = Item.query.order_by(Item.id.desc()).all()
    return render_template('index.html', items=items)

# 分类页
@app.route('/category/<category>')
def category_page(category):
    items = Item.query.filter_by(category=category).order_by(Item.id.desc()).all()
    return render_template('index.html', items=items, current_category=category)

# 发布物品页面
@app.route('/post', methods=['GET', 'POST'])
def post_item():
    if request.method == 'POST':
        name = request.form['name']
        price = float(request.form['price'])
        description = request.form['description']
        category = request.form['category']
        contact = request.form['contact']
        
        # 处理图片上传
        image = None
        if 'image' in request.files:
            file = request.files['image']
            if file.filename != '':
                filename = secure_filename(file.filename)
                file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                file.save(file_path)
                image = f'uploads/{filename}'
        
        # 创建新物品
        new_item = Item(
            name=name,
            price=price,
            description=description,
            category=category,
            contact=contact,
            image=image
        )
        
        db.session.add(new_item)
        db.session.commit()
        
        return redirect(url_for('index'))
    
    return render_template('post.html')

# 搜索功能
@app.route('/search', methods=['GET'])
def search():
    keyword = request.args.get('keyword', '')
    if keyword:
        items = Item.query.filter(
            (Item.name.contains(keyword)) | 
            (Item.description.contains(keyword))
        ).order_by(Item.id.desc()).all()
    else:
        items = Item.query.order_by(Item.id.desc()).all()
    
    return render_template('index.html', items=items, search_keyword=keyword)

if __name__ == '__main__':
    app.run(debug=True, port=5000)